package org.xs.web.http.i18n;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.xs.web.http.exception.NotFoundException;
import org.xs.web.util.Resources;

public class Properties {

	private MessageMap properties = null;
	private String fileName;
	private long fileLastModify = 0l;
	public boolean hasBeanReload = false;
	
	private File file = null;
	
	public Properties(String fileName){
		this.fileName = fileName;
		validate();
	}

	private boolean validate(){
		URL url = Resources.getResource(fileName);
		if(url == null) throw new NotFoundException(fileName+" can not found ");
		file = new File(url.getFile());
		return true;
	}
	
	
	public boolean change(){
		return hasBeanReload;
	}
	
	public MessageMap load(){
		BufferedReader reader = null;
		if(file.lastModified() > fileLastModify){
			hasBeanReload = true;
			try {
				Map<String,String> temp = new HashMap<String, String>();
				reader = new BufferedReader(new FileReader(file));
				String key,value = null;
				String line = null;
				int index = -1;
				while(reader.ready()){
					line = reader.readLine();
					index = line.indexOf('=');
					if(index > -1){
						key = line.substring(0,index);
						value = line.substring(index+1,line.length());
						temp.put(key.trim(), value.trim());
					}
					
				} 
				fileLastModify = file.lastModified();
				properties=  new MessageMap(temp);
			} catch (Exception e) {
				throw new NotFoundException(fileName+" can not found ");
			}finally{
				if(reader != null){
					try {
						reader.close();
					} catch (IOException e) {
						 //ignore
					}
				}
			}
			
		}else{
			hasBeanReload = false;
		}
		return properties;
	}
	
	
	
}
